﻿using IMES.Common.Domain.DariusModel;
using IMES.Common.Dtos;
using IMES.Common.Infrastructure;
using MediatR;

namespace Darius.API.Application.Commands
{
    public class LoginHandler : IRequestHandler<LoginCommand, Result>
    {
        private readonly IBaseRepositorys<Users> userRepository;
        private readonly ILogger<LoginHandler> logger;

        public LoginHandler(IBaseRepositorys<Users> userRepository, ILogger<LoginHandler> logger)
        {
            this.userRepository = userRepository;
            this.logger = logger;
        }
        /// <summary>
        /// 登录
        /// </summary>
        /// <param name="request"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        public async Task<Result> Handle(LoginCommand request, CancellationToken cancellationToken)
        {
            try
            {
                var result = new Result() { Code = (int)CodeEnum.search };
                var list = userRepository.GetAll().Where(x => x.UserAccount == request.UserAccount && x.UserPwd == request.UserPwd).FirstOrDefault();
                if (list != null)
                {
                    result.Data = list;
                    result.Messege = "登录成功";
                    logger.LogInformation("登录成功");

                }
                else
                {
                    result.Messege = "用户名或密码错误";
                    logger.LogInformation("用户名或密码错误");
                }
                return result;
            }
            catch (Exception ex)
            {
                logger.LogError(ex, "登录失败");
                return new Result() { Code = (int)CodeEnum.error, Messege = "登录失败" };
            }
        }
    }
}
